<?
    require_once("config.php");
    require_once("objects/form_elements.php");
    require_once("objects/editable_form_elements.php");
    require_once("objects/advanced_image_viewer.php");
    require_once("objects/addrstring.php");
    
    if (AuthManager::CheckPermissions(AuthConstants::NOT_LOGGED_IN)) {
	Functions::PrintHeader("Not Logged In");
	ErrorMessage::Show("Error!","You must be logged in to view listings!  If you need a guest account, you can register for one <a href='guest.php'>here</a>");
	Functions::PrintFooter();
    }
    
    // this is for handling complex structure data (like checkboxes)
    class EditableFormPostHandler {
        static function GetDataFor($structure) {
            switch ($structure['type']) {
                case "checkbox":
                    $options = explode(',',$structure['options']);
                    $save = array();
                    $count = 0;
                    foreach ($options as $option) {
                        $name = "formitem_$structure[id]_checkbox_$count";
                        if ($_POST[$name]) {
                            $save[SettingManager::EncodeSettingName($option)] = 1;
                        }
                        $count++;
                    }
                    foreach ($save as $option=>$value) {
                        $save[$option] = "$option:$value";
                    }
                    return implode(";",$save);
                break;
                default:
                    return $_POST['formitem_' . $structure['id']];
            }
        }
    }
    
    if ($_POST) {
        // first things first -- create or update the actual listing
        $dataid = $_POST['dataid'];
        $updated = array(
            'address_line1' => $_POST['address_line1'],
            'address_line2' => $_POST['address_line2'],
            'city' 			=> $_POST['city'],
            'state' 		=> $_POST['state'],
            'zip'	 		=> $_POST['zip'],
            'rent' 			=> $_POST['rent'],
            'availableon'	=> strtotime($_POST['availableon'] . "01:00am"),
	        'postedon'	    => time(),
            'listed'        => $_POST['listed'],
            'landlordid'	=> $_POST['landlordid']
        );
        /*
        echo "<pre>" . print_r($_POST,true) . "</pre>";
        echo "<pre>" . print_r($updated,true) . "</pre>";
        */
        if (!isset($dataid)) {
            $query = QueryTools::CreateQuery($updated,'listings');
            try { DBM::Execute($query); } catch (ComplexException $exception) { 
            	FatalMessage::Show($exception->Title(),$exception->Message());
            }
            $dataid = DBM::LastInsertID();
        }
        else DBM::Execute(QueryTools::CreateQuery($updated,'listings','update',$_POST['dataid']));
        
        // now deal with the options and custom stuff
        $structures = DBM::FetchAllRows("SELECT * FROM listing_structure ORDER BY location;");
        
        foreach ($structures as $structure) {
            $data = EditableFormPostHandler::GetDataFor($structure);
            $query = '';
            if ($_POST['dataid'])
                $query = "UPDATE listing_data SET data='$data' WHERE structureid=$structure[id] AND listingid=$_POST[dataid];";
            else 
                $query = "INSERT INTO listing_data (`listingid`,`structureid`,`data`) VALUES ($dataid,$structure[id],'$data');";
            echo $query . "<br>";
            DBM::Execute($query);

	    // this is a fix --
	    // its here in case the listing structure gets changed after a listing has been created.
	    // if that's the case, then the listing_data isn't going to contain a record of that structure for that listing
	    // this inserts that structure information for the specific listing id.
	    if (DBM::AffectedRows() == 0) {
		$query = "INSERT INTO listing_data (`listingid`,`structureid`,`data`) VALUES ($dataid,$structure[id],'$data');";
		DBM::Execute($query);
	    }
        }
        
        if (!$_POST['addphotos'])
            header("Location: listing.php?action=view&id=$dataid");
        else
            header("Location: photos.php?id=$dataid");
    }
    else {
        $action = strtoupper($_GET['action'][0]).substr($_GET['action'],1);
        $menu = new Menu("Actions");
        $menu->AddItem(new MenuItem("Edit Listing Structure","admin_listingstructure.php",AuthConstants::ADMINISTRATORS));
        if ($_GET['action'] != 'edit') {
            if (isset($_GET['id']) && ((DBM::CountRows("SELECT * FROM listings WHERE id=$_GET[id] AND landlordid=" . AuthManager::GetUserID()) > 0) || (AuthManager::CheckPermissions(AuthConstants::ADMINISTRATORS)))) {
                $menu->AddItem(new MenuItem("Edit This Listing","listing.php?action=edit&id=$_GET[id]",array(AuthConstants::ADMINISTRATORS,AuthConstants::LANDLORDS)));
                $menu->AddItem(new MenuItem("Manage Photos","photos.php?id=$_GET[id]",array(AuthConstants::ADMINISTRATORS,AuthConstants::LANDLORDS)));
            }
        }
        $menu->AddItem(new MenuItem("Edit My Listings","listings.php",array(AuthConstants::LANDLORDS)));
        $menu->AddItem(new MenuItem("Contact Landlord","messages.php?action=compose&listingid=$_GET[id]",array(AuthConstants::GUESTS,AuthConstants::STUDENTS)));
        
        MenuManager::AddMenu("$action Listing",$menu);
        
        
        Functions::PrintHeader("$action Listing");
        
        // make sure noone is editing listings when they shouldn't be
        if ($_GET['action'] != "view") {
            if (!AuthManager::CheckPermissions(array(AuthConstants::LANDLORDS,AuthConstants::ADMINISTRATORS))) {
                ErrorMessage::Show("Can't view that","Sorry, you need to access this page by either searching for or browsing listings.");
                Functions::PrintFooter();
                die();
            }
        }
        
        $action = $_GET['action'];
        $dataid = ($_GET['id'] ? $_GET['id'] : null);
        try {
        	$data = (isset($dataid) ? DBM::FetchRow("SELECT * FROM listings WHERE id=$dataid;") : null);
        }
        catch (ComplexException $e) { FatalMessage::Show($e->Title(),$e->Message()); }
        
        if ($_GET['id'] && $data == null) {
            ErrorMessage::Show("No Such Listing","Sorry, that listing doesn't exist.");
        }
	else if ($_GET['action'] == "view" && $data == NULL) {
	    ErrorMessage::Show("No Listing Specified","Sorry, no listing was specified");
	}
        else if ($action == "edit" && !AuthManager::ListingBelongsTo($dataid)) {
            ErrorMessage::Show("Not Editable","Sorry, you don't have permissions to edit that listing.");
        }
        else {
            echo "<form method='POST' action='listing.php'>";
            if ($dataid) {
            	echo "<input type='hidden' name='listingid' value='$dataid' />";
            }
            $sections = array();
            
            // Do the google maps stuff
            if (SettingManager::GetSetting("google maps enabled") && $_GET['id'] && $_GET['action'] == "view") {
                ?>
                <script type='text/javascript' language='Javascript' src='<?=SettingManager::GetSetting("google maps api src")?>'></script>
                
                <div style='border:solid 3px black; background:#dddddd; height:300px;margin-bottom:20px;'>
                    <div class='map' id='listingmap' style='position:relative;float:left;width:100%; height:300px;'></div>
                </div>
                
                <script type='text/javascript'>
                    var map;
                    var geocoder;
                    var marker;
                    
                    var Location = Class.create({
                        info : null,
                        address : '',
                        lat : 0,
                        lng : 0,
                        listinginfo : {},
                        
                        initialize : function (address_str,lat,lng) {
                            this.address = address_str;
                            this.lat = lat;
                            this.lng = lng;
                        },
                        setListingInfo : function (varname,value) {
                            this.listinginfo[varname] = value;
                        },
                        render : function() {
                            return;
                        
                            var marker = new GMarker(new GLatLng(this.lat,this.lng));
                            map.addOverlay(marker);
                            
                            var infohtml = this.address + '<br><hr />';
                            for (var prop in this.listinginfo) {
                                infohtml += "<b>" + prop + "</b>: " + this.listinginfo[prop] + "<br>";
                            }
                            
                            marker.openInfoWindowHtml(infohtml);
                        }
                    });
                    
                    function distanceFrom(loc) {
                        var directions = new GDirections();
                        dirstr = "from: <?=SettingManager::GetSetting("google maps school address")?> to: " + loc.address;
                        directions.load(dirstr,{getSteps:true});
                        
                        
                        return directions.getDistance();
                    }
                    
                    lookuphandler = function(response) {
                        map.clearOverlays();
                        if (!response || response.Status.code != 200) {
                            alert("ERROR: This seems to be an invalid address and the location could not be mapped.");
                        } else {
                            place = response.Placemark[0];

                            var loc = new Location(place.address,coords[1], coords[0]);
                            
                            
                            marker = new GMarker(new GLatLng(coords[1],coords[0]));
                            map.addOverlay(marker);
                            marker.openInfoWindowHtml(place.address + '<br>' + 
                              '<b>Distance From Campus:</b> Approximately ' + distanceFrom(loc));
                        }
                    }
                    
                    // still need the onLoad function
                    Event.observe(document,"load",function() {
                        if (GBrowserIsCompatible()) {
                            map = new GMap2(document.getElementById("listingmap"));
                            map.setCenter(new GLatLng(42.733150,-73.67888),15);
                            geocoder = new GClientGeocoder();
                            
                            <?
                
                            if ($data) {
                                $addrstring = "$data[address_line1] " . ($data['address_line2'] ? ", $data[address_line2]" : '') . ", $data[city], $data[state] $data[zip]";
                                if ($data['lat'] && $data['long']) {
                                ?>
                                    map.setCenter(new GLatLng(<?=$data['lat']?>,<?=$data['long']?>),15);
                                    var loc = new Location("<?=$addrstring?>");
                                    loc.setListingInfo("Distance from Campus",getDistance(loc));
                                    loc.render();
                                <?
                                }
                                else {
                                ?>
                                    geocoder.getLocations("<?=$addrstring?>",lookuphandler);
                                <?
                                }
                            }
                            
                            ?>
                        }
                    });
                </script>
                <?
            }
            
            if ($action == "view" && isset($_GET['id'])) {
                $listingobj = ListingManager::FetchListing($_GET['id']);
                if (!$listingobj->info['listed']) {
                    WarningMessage::Show("Listing Not Available","This listing is not currently available for rent.");
                }
            }
            // render the basic listing form
            ?>
            <table class='wide cgltable'>
                <thead>
                    <tr>
                        <th colspan='2'>Basic Listing Information</th>
                    </tr>
                </thead>
                <tr>
                    <?
                        if ($_GET['id'] && ListingImageManager::HasImages($_GET['id'])) {
                            $colcount = SettingManager::GetSetting("listing_images_per_row");
                            if ($colcount == 0) $colcount = 4;
                            
                            // show the images for this listing
                            $info = ListingImageManager::GetImages($_GET['id'],true);
                            $images = array_keys($info);
                            $comments = array_values($info);
                            $viewer = new AdvancedImageViewer($images,0);
                            $viewer->AddComments($comments);
                            echo "<td>";
                            echo $viewer;
                            
                            echo "<script type='text/javascript'>aiv_initialize()</script>";
                            echo "</td>";
                        }
                        
                        if ($action != "view") {
                        	echo "<input type='hidden' name='landlordid' value='" . AuthManager::GetUserID() . "' />";
                        }
                    ?>
                <td valign='top' style='vertical-align:top;' class='wide'>
                <table class='wide'>
                <?php if ($action == "view" && AuthManager::AuthLevelMatches(array(AuthConstants::STUDENTS,AuthConstants::GUESTS,AuthConstants::ADMINISTRATORS))) { ?>
                    <tr>
                        <td class='label'>Favorite</td>
                        <td><img src='<?php
                            if ($listingobj->IsFavorite())
                                echo ThemeManager::GetImage("favorite");
                            else
                                echo ThemeManager::GetImage("favorite_bw");
                        ?>' onClick='favorite(<?=$_GET['id']?>)' id='favoriteimage_<?=$_GET['id']?>' style='cursor:pointer;' /></td>
                    </tr>
                 <?php } ?>
                    <tr>
                        <td class='label' style='width:200px;'>Address</td>
                        <td><?
                            if ($action == "view") {
                                echo new AddrString($data,true);
                            }
                            else {
                                
                                $val = ($dataid ? DBM::FetchOne("SELECT address_line1 FROM listings WHERE id=$dataid;") : "");
                                $val2 = ($dataid ? DBM::FetchOne("SELECT address_line2 FROM listings WHERE id=$dataid;") : "");
                                echo "<input type='text' name='address_line1' value='$val' /><br>";
                                echo "<input type='text' name='address_line2' value='$val2' /><br />";
                                echo "Please do not put any extra information in the address field.  There is space at the end of the form to put any extra information you'd like to mention about the listing.  Landlords who violate this may have their accounts subject to suspension and their listings subject to deletion.";
                            }
                        ?></td>
                    </tr>
                    <?php if ($action != "view") { ?>
                    <tr>
                        <td class='label'>City</td>
                        <td><?
                            if ($action == "view") echo $data['city'];
                            else echo "<input type='text' name='city' value='$data[city]' />";
                            ?>
                        </td>
                    </tr>
                    <tr>
                        <td class='label'>State</td>
                        <td>
                            <?
                            if ($action == "view") echo $data['state'];
                            else {
                                echo "<select name='state'>";
                                $states = array(
                                    "AL" => "ALABAMA",
                                    "AK" => "ALASKA",
                                    "AS" => "AMERICAN SAMOA",
                                    "AZ" => "ARIZONA",
                                    "AR" => "ARKANSAS",
                                    "CA" => "CALIFORNIA",
                                    "CO" => "COLORADO",
                                    "CT" => "CONNECTICUT",
                                    "DE" => "DELAWARE",
                                    "DC" => "DISTRICT OF COLUMBIA",
                                    "FM" => "FEDERATED STATES OF MICRONESIA",
                                    "FL" => "FLORIDA",
                                    "GA" => "GEORGIA",
                                    "GU" => "GUAM",
                                    "HI" => "HAWAII",
                                    "ID" => "IDAHO",
                                    "IL" => "ILLINOIS",
                                    "IN" => "INDIANA",
                                    "IA" => "IOWA",
                                    "KS" => "KANSAS",
                                    "KY" => "KENTUCKY",
                                    "LA" => "LOUISIANA",
                                    "ME" => "MAINE",
                                    "MH" => "MARSHALL ISLANDS",
                                    "MD" => "MARYLAND",
                                    "MA" => "MASSACHUSETTS",
                                    "MI" => "MICHIGAN",
                                    "MN" => "MINNESOTA",
                                    "MS" => "MISSISSIPPI",
                                    "MO" => "MISSOURI",
                                    "MT" => "MONTANA",
                                    "NE" => "NEBRASKA",
                                    "NV" => "NEVADA",
                                    "NH" => "NEW HAMPSHIRE",
                                    "NJ" => "NEW JERSEY",
                                    "NM" => "NEW MEXICO",
                                    "NY" => "NEW YORK",
                                    "NC" => "NORTH CAROLINA",
                                    "ND" => "NORTH DAKOTA",
                                    "MP" => "NORTHERN MARIANA ISLANDS",
                                    "OH" => "OHIO",
                                    "OK" => "OKLAHOMA",
                                    "OR" => "OREGON",
                                    "PW" => "PALAU",
                                    "PA" => "PENNSYLVANIA",
                                    "PR" => "PUERTO RICO",
                                    "RI" => "RHODE ISLAND",
                                    "SC" => "SOUTH CAROLINA",
                                    "SD" => "SOUTH DAKOTA",
                                    "TN" => "TENNESSEE",
                                    "TX" => "TEXAS",
                                    "UT" => "UTAH",
                                    "VT" => "VERMONT",
                                    "VI" => "VIRGIN ISLANDS",
                                    "VA" => "VIRGINIA",
                                    "WA" => "WASHINGTON",
                                    "WV" => "WEST VIRGINIA",
                                    "WI" => "WISCONSIN",
                                    "WY" => "WYOMING"
                                );
                                
                                foreach ($states as $abbrev=>$state) {
                                    $current = ($data['state'] ? $data['state'] : SettingManager::GetSetting("Default State"));
                                    echo "<option value='$abbrev'" . ($current == $abbrev ? " selected='selected'" : "") . ">$state</option>";
                                }
                                echo "</select>";
                            }
                            ?>
                        </td>
                    </tr>
                    <tr>
                        <td class='label'>ZIP Code</td>
                        <td><?
                            if ($action == "view") echo $data['zip']; 
                            else echo "<input type='text' name='zip' value='$data[zip]' />";
                            ?>
                        </td>
                    </tr>
                    <?php } // end if action = edit
                    ?>
                    <tr>
                        <td class='label'>
                            Lease Begins On<br />
                        </td>
                        <td><?
                            if ($action == "view") echo ($data['availableon'] ? date("F d, Y",$data['availableon']) : 'Contact Landlord');
                            else {
                                echo "<input type='hidden' name='availableon' id='availableon' value='" . ($data['availableon'] ? date("F d, Y",$data['availableon']) : '') . "' />";
                                echo "<span id='availableon_visible'>" . (isset($data['availableon']) ? date("F d, Y",$data['availableon']) : "Unspecified") . "</span>";
                                echo "<input type='button' style='margin-left:15px;' id='availableon_trigger' value='Select Date' />";
                                ?>
                                <br />
                                <span style='font-size:8pt'>You only need to select a starting lease date if you are immediately making the listing public.  You do not need to select a lease date for private listings.</span>
                                    <script type='text/javascript'>
                                        Calendar.setup({
                                            inputField : "availableon",
                                            trigger    : "availableon_trigger",
                                            onSelect   : function() {
                                                // save the new value in a hidden field
                                                var date = this.selection.get();
                                                
                                                // show the value to the user so they can read it
                                                date = Calendar.intToDate(date);
                                                date = Calendar.printDate(date, "%B %d, %Y");
                                                $("availableon_visible").innerHTML = date;
                                                $("availableon").value = date;
                                                
                                                this.hide();
                                            }
                                        });
                                    </script>
                                <?php
                            }
                            ?>
                        </td>
                    </tr>
                    <?php if ($action != "view") { ?>
                    <tr>
                        <td class='label'>Show In Listings?<br /></td>
                        <td>
                            <label><input type='radio' name='listed' value='1' checked /> Yes, I would like this listing to be publicly viewable</label><br />
                            <label><input type='radio' name='listed' value='0' /> No, this listing is not currently available</label>
                            <hr />
                            <br />
                            <span style='font-size:8pt;'>If yes, this listing will become publicly viewable as soon as it is saved.  If no, this listing will be saved in 'My Listings' and you will be able to list it at your discretion.</span>
                        </td>
                    </tr>
                    <?php } ?>
                    <tr>
                        <td class='label'>Rent per month</td>
                        <td>
                            <?php
                                if ($action == "view") { echo '$' . $data['rent']; }
                                else {
                                    ?>
                                    <div id='moneysymbol' style='font-size:14pt; position:absolute;z-index:10000; padding-left:6px; padding-top:4px;'>$</div>
                                    <?php
                                    echo "<input type='text' onKeyUp='this.value=(this.value.indexOf(\"$\") >= 0 ? this.value.substring(1) : this.value)' style='position:relative; float:left; padding-right:-15px; padding-left:15px;' name='rent' value='$data[rent]' />";
                                }
                            ?>  
                        </td>
                    </tr>
                    <?php 
                        if ($action == "view") { 
                            $landlordquery = "SELECT * FROM guests WHERE id=$data[landlordid];";
                            $landlordinfo = DBM::FetchRow($landlordquery);
                            
                        ?>
                        <tr>
                            <td class='label'>Landlord</td>
                            <td><a href='profile.php?id=<?=$landlordinfo['id']?>'><?=$landlordinfo['name']?></a></td>
                        </tr>
                    <?php } ?>
                </table>
            </td>
            </tr>
            </table>
            <br />
            <? if ($action != "view") { ?>
            <table class='wide cgltable'>
            <thead>
                <tr>
                    <th>Photos</th>
                </tr>
            </thead>
                <tr>
                    <td style='padding:20px; text-align:center;'><label><input type='checkbox' name='addphotos' />Check this box if you would like to add photos</label><br><br><span style='font-size:8pt'>You will be allowed to upload photos after saving the listing.  Upon saving, you will automatically be directed to the upload form.</span></td>
                </tr>
            </table>
            <br>
            <?
            }
            // and now render everything else
            $query = "SELECT * FROM listing_structure ORDER BY location ASC;";
            $lineitems = DBM::FetchAllRows($query);
            
            if ($dataid) echo "<input type='hidden' name='dataid' value='$dataid' />\n";
            
            // sections are made up of tables broken up by the header elements
            
            $curtable = null;
            
            foreach ($lineitems as $lineitem) {
                if ($lineitem['type'] == 'header') {
                    if ($curtable) $sections[] = $curtable;
                    $curtable = new HTMLControl("table");
                    $curtable->SetAttribute('class','wide cgltable');
                    $theader = new HTMLControl("thead");
                    $row = new HTMLControl("tr");
                    
                    $header = new EditableHeader($lineitem['id'],false,$dataid);
                    $cell = new HTMLControl("th",$header);
                    $cell->attributes->colspan = 2;
                    $row->AddChild($cell);

                    $theader->AddChild($row);
                    $curtable->AddChild($theader);
                }
                else {
                    $row = new HTMLControl("tr");
                    
                    $label = new HTMLControl("td",$lineitem['title']);
                    $label->styles->width = "200px";
                    $label->SetAttribute('class','label');
                    $row->AddChild($label);
                    
                    $data = new HTMLControl("td");
                    $control = null;
                    
                    $haspermissions = AuthManager::AuthLevelMatches(array(AuthConstants::ADMINISTRATORS,AuthConstants::LANDLORDS));
                    $editable = ($_GET['action'] != "view" && $haspermissions ? true : false);
                    
                    switch ($lineitem['type']) {
                        case "checkbox":
                            $control = new EditableCheckboxes($lineitem['id'],$editable,$dataid);
                        break;
                        case "radio":
                            $control = new EditableRadio($lineitem['id'],$editable,$dataid);
                        break;
                        case "select":
                            $control = new EditableSelect($lineitem['id'],$editable,$dataid);
                        break;
                        case "textarea":
                            $control = new EditableTextarea($lineitem['id'],$editable,$dataid);
                        break;
                        default:
                            $control = new EditableTextfield($lineitem['id'],$editable,$dataid);
                    }
                    
                    $data->AddChild($control);
                    $row->AddChild($data);
                    $curtable->AddChild($row);
                }
            }
            
            $sections[] = $curtable;
            
            foreach ($sections as $table) {
                echo $table->__toString() . "<br>";
            }
            
            if ($action != "view")
                echo "<hr /><input type='submit' value='Save Listing' />";
            echo "</form>";
            
        }
        Functions::PrintFooter();
    }
?>
